/**
 *
 * @param id
 * @param direction
 * @constructor
 */
function Snake(id) {
  this.id = id;
  this.span = 50;
  this.status = true;
  this.direction = '';
  this.data = [];
  this.speed = 5;
  this.tempSpeed = 0;
  this.revive = false;
  this.type = '';
}

Snake.prototype.setProp = function (obj) {
  if (obj) {
    for (var k in obj) {
      this[k] = obj[k];
    }
  }
  return this;
}

Snake.prototype.setDirection = function (direction) {
  if (this._directionMap[this.direction] !== direction) {
    this.direction = direction;
  }
}

Snake.prototype.nextStep = function (warm) {
  this.tempSpeed++;
  if (this.tempSpeed < this.speed) {
    return;
  }
  if (this.status === true) {
    this.tempSpeed = 0;
    return this['_' + this.direction]()._dealWarm(warm);
  }
  return this;
}

Snake.prototype.changeRevive = function () {
  this.revive = !this.revive;
  return this;
}

Snake.prototype._directionMap = {
  "up": 'down',
  "down": 'up',
  "left": 'right',
  "right": 'left'
}

Snake.prototype._dealWarm = function (warm) {
  if (this.status !== false) {
    // eat warm
    if (warm.status === 'fixed' && this.data[0].x === warm.data[0].x && this.data[0].y === warm.data[0].y) {
      warm.status = false;
      warm.data.length = 0;
      if (warm.type && warm.type === 'mushroom') {
        this.speed--;
        if (this.speed < 1) {
          this.speed = 1;
        }
        console.log(this.speed);
      }
    } else {
      this.data.pop();
    }
  }
  return this;
}

Snake.prototype._up = function (warm) {
  if (this.data[0].y > 0) {
    this.data.unshift({x: this.data[0].x, y: this.data[0].y - 1});
  } else {
    this.status = false;
  }
  return this;
}

Snake.prototype._down = function (warm) {
  if (this.data[0].y + 1 < this.span) {
    this.data.unshift({x: this.data[0].x, y: this.data[0].y + 1});
  } else {
    this.status = false;
  }
  return this;
}

Snake.prototype._left = function (warm) {
  if (this.data[0].x > 0) {
    this.data.unshift({x: this.data[0].x - 1, y: this.data[0].y});
  } else {
    this.status = false;
  }
  return this;
}

Snake.prototype._right = function (warm) {
  if (this.data[0].x + 1 < this.span) {
    this.data.unshift({x: this.data[0].x + 1, y: this.data[0].y});
  } else {
    this.status = false;
  }
  return this;
}

module.exports = Snake;
